package com.es.www.transaction.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.stereotype.Component;

import com.es.www.transaction.util.JdbcUtil;

/**
 * @Created by michangtao
 * @Date 2022/2/9 15:43
 * @Description
 */
@Component
public class FinanceDao {

    public void addMoney(Long id, Integer num) {
        try {
            //从ThreadLocal中取事务，保证addMoney和substractMoney使用的是同一个connection
            Connection connection = JdbcUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement("update test_employee set salary = salary + ? where id = ?");
            statement.setInt(1, num);
            statement.setLong(2,id);
            statement.executeUpdate();
            statement.close();
            connection.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void substractMoney(Long id, Integer num) {
        try {
            Connection connection = JdbcUtil.getConnection();
            PreparedStatement statement = connection.prepareStatement("update test_employee set salary = salary - ? where id = ?");
            statement.setInt(1, num);
            statement.setLong(2,id);
            statement.executeUpdate();
            statement.close();
            connection.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
